Skip to content

fix: date level stats #1312

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 15, 2025
Merged

Conversation

nikhilsinhaparseable
Copy link
Contributor

@nikhilsinhaparseable nikhilsinhaparseable commented May 14, 2025

read all stream.json files for a dataset
get sum of stats for a given date from the manifest list in snapshot

no need to calculate querier / ingestor stats separately

fix applicable for -
/api/v1/logstream//stats?date=yyyy-mm-dd
and
/api/prism/v1/home

Summary by CodeRabbit

  • Refactor
    • Simplified and unified the process for fetching daily stats by renaming and consolidating functions.
    • Streamlined logic for obtaining stats, removing redundant steps and unnecessary data aggregation.
    • Updated function signatures and imports to reflect these changes, resulting in a cleaner and more maintainable codebase.
  • Bug Fixes
    • Improved accuracy of daily stats by eliminating duplicate aggregation and focusing on a single source of data.
    • Enhanced query parameter validation with clearer error handling for invalid or missing parameters.

read all stream.json files for a dataset
get sum of stats for a given date from the manifest list in snapshot

no need to calculate querier / ingestor stats separately
Copy link
Contributor

coderabbitai bot commented May 14, 2025

Walkthrough

The changes rename the function fetch_daily_stats_from_ingestors to fetch_daily_stats and update all related imports and function calls accordingly. The code is simplified by removing querier stats aggregation, streamlining the logic to fetch and return daily stats from ingestor data only. Some function signatures are adjusted to reflect these changes. Additionally, query parameter parsing and validation are improved, and a new error variant for invalid query parameters is introduced.

Changes

File(s) Change Summary
src/handlers/http/cluster/mod.rs Renamed fetch_daily_stats_from_ingestors to fetch_daily_stats; no logic changes.
src/handlers/http/modal/query/querier_logstream.rs Updated imports and function calls to use fetch_daily_stats; removed querier stats logic; simplified filtering; improved query parameter parsing and validation.
src/prism/home/mod.rs Updated imports and function signatures to use fetch_daily_stats; simplified get_stream_stats_for_date logic by removing stream parameter and asynchronous calls.
src/handlers/http/logstream.rs Added InvalidQueryParameter(String) variant to StreamError enum; updated error status code mapping to 400 Bad Request.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant QueryHandler
    participant ClusterModule

    Client->>QueryHandler: HTTP GET /stats?date=YYYY-MM-DD
    QueryHandler->>QueryHandler: Parse and validate query parameters
    QueryHandler->>ClusterModule: fetch_daily_stats(date, stream_meta_list)
    ClusterModule-->>QueryHandler: Stats
    QueryHandler-->>Client: JSON response with stats or error
Loading

Suggested labels

for next release

Suggested reviewers

  • parmesant

Poem

A function renamed, a path made clear,
Stats now fetched with less to fear.
Querier sums have gone away,
Ingestor data leads the way.
Simpler code, a lighter load—
Hopping forward down the road! 🐇✨

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7f3e752 and 533890a.

📒 Files selected for processing (2)
  • src/handlers/http/logstream.rs (2 hunks)
  • src/handlers/http/modal/query/querier_logstream.rs (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/handlers/http/modal/query/querier_logstream.rs
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Build Default x86_64-pc-windows-msvc
  • GitHub Check: Build Default aarch64-apple-darwin
  • GitHub Check: Build Default x86_64-apple-darwin
  • GitHub Check: Build Kafka aarch64-apple-darwin
  • GitHub Check: Build Default aarch64-unknown-linux-gnu
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
  • GitHub Check: Quest Smoke and Load Tests for Standalone deployments
  • GitHub Check: coverage
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments
  • GitHub Check: Build Kafka x86_64-unknown-linux-gnu
🔇 Additional comments (2)
src/handlers/http/logstream.rs (2)

527-528: Good addition of a specific error variant for invalid query parameters.

Adding a dedicated error variant for invalid query parameters will provide more detailed and specific error handling throughout the codebase, improving error reporting capabilities.


564-564: Appropriate status code mapping for the new error variant.

The status code of 400 (Bad Request) is correctly assigned for the InvalidQueryParameter error, which aligns with HTTP standards for client-side errors.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🔭 Outside diff range comments (1)
src/handlers/http/cluster/mod.rs (1)

396-421: 🛠️ Refactor suggestion

Use NaiveDate comparison to avoid repeated string allocations and potential locale issues

time_lower_bound.date_naive().to_string() == date converts every manifest’s date into a heap-allocated String on every iteration and compares it to the user-supplied string.
A cheaper and less error-prone approach is:

  1. Parse the incoming &str once into NaiveDate.
  2. Compare the two NaiveDate values directly.
-pub fn fetch_daily_stats(
-    date: &str,
+pub fn fetch_daily_stats(
+    date: &str,
     stream_meta_list: &[ObjectStoreFormat],
 ) -> Result<Stats, StreamError> {
-    // for the given date, get the stats from the ingestors
+    // For the given date, collect stats from all manifests
     let mut events_ingested = 0;
     let mut ingestion_size = 0;
     let mut storage_size = 0;
 
-    for meta in stream_meta_list.iter() {
-        for manifest in meta.snapshot.manifest_list.iter() {
-            if manifest.time_lower_bound.date_naive().to_string() == date {
+    let target_date = chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d")
+        .map_err(|e| StreamError::Custom {
+            msg: format!("invalid date '{}': {e}", date),
+            status: http::StatusCode::BAD_REQUEST,
+        })?;
+
+    for meta in stream_meta_list {
+        for manifest in &meta.snapshot.manifest_list {
+            if manifest.time_lower_bound.date_naive() == target_date {
                 events_ingested += manifest.events_ingested;
                 ingestion_size += manifest.ingestion_size;
                 storage_size += manifest.storage_size;
             }
         }
     }

Benefits
• Eliminates per-iteration String allocations.
• Guards against malformed dates in the query string.
• Avoids subtle bugs caused by locale-dependent to_string() formats.

🧹 Nitpick comments (3)
src/handlers/http/modal/query/querier_logstream.rs (1)

179-185: Redundant total_stats re-construction

stats already owns events, ingestion, and storage; wrapping it into a new Stats with identical fields is unnecessary:

-let total_stats = Stats {
-    events: stats.events,
-    ingestion: stats.ingestion,
-    storage: stats.storage,
-};
-let stats = serde_json::to_value(total_stats)?;
+let stats = serde_json::to_value(&stats)?;

Reduces one allocation and keeps the intent clearer.

src/prism/home/mod.rs (2)

221-224: Avoid cloning heavy metadata vectors in hot path

stream_wise_meta.values().map(|meta| get_stream_stats_for_date(date.clone(), meta.clone()))
clones the full Vec<ObjectStoreFormat> for every stream/date pair, which may be large.

You can pass a slice to avoid clones:

-.map(|meta| get_stream_stats_for_date(date.clone(), meta.clone()));
+.map(|meta| get_stream_stats_for_date(date.clone(), meta));

and adapt the callee to accept &[ObjectStoreFormat].

This reduces memory churn and speeds up the home-page stats aggregation.


249-252: Propagate “no-data” condition explicitly

If fetch_daily_stats returns zeroed stats because meta contained no manifests for that date, the home page silently shows zeros. Consider returning None for “no data” and filtering it out upstream to distinguish between “0 events” and “no data”.

if stats.events == 0 && stats.ingestion == 0 && stats.storage == 0 {
    return Ok(None);
}

This yields a more accurate UI/UX.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3d844b3 and d572881.

📒 Files selected for processing (3)
  • src/handlers/http/cluster/mod.rs (1 hunks)
  • src/handlers/http/modal/query/querier_logstream.rs (3 hunks)
  • src/prism/home/mod.rs (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Build Default x86_64-pc-windows-msvc
  • GitHub Check: Build Default aarch64-apple-darwin
  • GitHub Check: Build Default x86_64-apple-darwin
  • GitHub Check: Build Default aarch64-unknown-linux-gnu
  • GitHub Check: Build Kafka aarch64-apple-darwin
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
  • GitHub Check: Quest Smoke and Load Tests for Standalone deployments
  • GitHub Check: coverage
  • GitHub Check: Build Kafka x86_64-unknown-linux-gnu
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments
🔇 Additional comments (2)
src/handlers/http/modal/query/querier_logstream.rs (2)

167-177: Vector rename looks good

Pure renaming (ingestor_stream_jsonsstream_jsons) with no semantic impact.
No concerns here.


39-43:

❓ Verification inconclusive

Possible double-counting after broadening the file filter

The previous predicate filtered only files starting with .ingestor to ensure each manifest is counted exactly once.
After the change, the predicate accepts all "stream.json" files, e.g. those prefixed with .ingestor, .querier, .indexer, etc.
If other components write their own stream.json, the same manifests may now be aggregated multiple times, inflating the daily stats.

Please confirm that only ingestors produce stream.json files, or reinstate a stricter predicate such as:

-Box::new(|file_name| file_name.ends_with("stream.json"))
+Box::new(|file_name| file_name.starts_with(".ingestor") && file_name.ends_with("stream.json"))

🏁 Script executed:

#!/bin/bash
# Locate all occurrences of the stream.json file filter
rg -n 'ends_with("stream.json")' -n .

# Show surrounding context for any Box::new predicates involving stream.json
rg -C5 'Box::new.*stream\.json' -n .

Length of output: 5013


Verify stream.json Origins to Avoid Double-Counting

I located six uses of the relaxed ends_with("stream.json") predicate across the codebase (e.g., in src/query/..., src/prism/home/mod.rs, src/storage/object_storage.rs, src/enterprise/utils.rs, and your handler src/handlers/http/modal/query/querier_logstream.rs). Unless every component’s stream.json files are uniquely scoped by directory (e.g. only ingestors write them under a .ingestor…/stream path), you risk counting the same manifest multiple times.

Please confirm that no non-ingestor components emit their own stream.json; if they do, narrow the filter:

- Box::new(|file_name| file_name.ends_with("stream.json"))
+ Box::new(|file_name| file_name.starts_with(".ingestor") && file_name.ends_with("stream.json"))
  • Files needing review:
    • src/handlers/http/modal/query/querier_logstream.rs (line 163)
    • src/query/mod.rs (line 475)
    • src/query/stream_schema_provider.rs (line 511)
    • src/prism/home/mod.rs (line 172)
    • src/storage/object_storage.rs (line 680)
    • src/enterprise/utils.rs (line 84)

coderabbitai[bot]
coderabbitai bot previously approved these changes May 14, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/handlers/http/modal/query/querier_logstream.rs (1)

146-147: Consider improving query string parameter validation.

The current approach to splitting the query string is fragile and could panic if the query string doesn't follow the expected format (e.g., if it has multiple parameters or none).

Consider using a more robust parsing approach:

-        let date_key = query_string.split('=').collect::<Vec<&str>>()[0];
-        let date_value = query_string.split('=').collect::<Vec<&str>>()[1];
+        let parts: Vec<&str> = query_string.split('=').collect();
+        if parts.len() != 2 {
+            return Err(StreamError::Custom {
+                msg: "Invalid query parameter format".to_string(),
+                status: StatusCode::BAD_REQUEST,
+            });
+        }
+        let date_key = parts[0];
+        let date_value = parts[1];
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d572881 and 7f3e752.

📒 Files selected for processing (2)
  • src/handlers/http/modal/query/querier_logstream.rs (3 hunks)
  • src/prism/home/mod.rs (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/prism/home/mod.rs
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Build Default x86_64-pc-windows-msvc
  • GitHub Check: Build Default aarch64-apple-darwin
  • GitHub Check: Build Default x86_64-apple-darwin
  • GitHub Check: Build Default aarch64-unknown-linux-gnu
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments
  • GitHub Check: Build Kafka aarch64-apple-darwin
  • GitHub Check: coverage
  • GitHub Check: Quest Smoke and Load Tests for Standalone deployments
  • GitHub Check: Build Kafka x86_64-unknown-linux-gnu
🔇 Additional comments (3)
src/handlers/http/modal/query/querier_logstream.rs (3)

39-39: Import refactoring reflects the unified stats approach.

The import change from fetch_daily_stats_from_ingestors to fetch_daily_stats aligns with the PR objective of consolidating the way date-level statistics are calculated rather than handling querier and ingestor stats separately.


163-163: Simplified file filtering logic matches the consolidation approach.

The filtering predicate has been simplified to include all files ending with "stream.json" rather than only those from ingestors. This change supports the PR objective of reading all stream files to aggregate stats instead of calculating them separately by component.


167-167: Renamed variable improves semantic clarity.

The variable rename from ingestor_stream_jsons to stream_jsons better reflects that we're now collecting all stream JSON files, not just those from ingestors.

Also applies to: 176-176

@nitisht nitisht merged commit 749a16f into parseablehq:main May 15, 2025
14 checks passed
@nikhilsinhaparseable nikhilsinhaparseable deleted the fix-home-stats branch May 15, 2025 06:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants